package vn.com.mybudget.common;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.net.URLEncoder;

import com.google.api.server.spi.IoUtil;


public class CommonUtil {
	static String[] viewExtensions = new String[] { "htm", "jsp", "html" };
	public static String currentPathContext = "";

	public static String GetExistingFile(String basePath) {
		for (int i = 0; i < viewExtensions.length; i++) {
			File f = new File(basePath + "." + viewExtensions[i]);
			if (f.exists()) {
				return basePath + "." + viewExtensions[i];
			}
		}
		return "";
	}

	public static Object CreateObjectInstance(String className) {
		Object object = null;
		try {
			Class classDefinition = Class.forName(className);
			object = classDefinition.newInstance();
		} catch (InstantiationException e) {
			System.out.println(e);
		} catch (IllegalAccessException e) {
			System.out.println(e);
		} catch (ClassNotFoundException e) {
			System.out.println(e);
		}
		return object;
	}

	public static String ReadFile(String fileName) {
		try {
			File f = new File(CommonUtil.currentPathContext + "\\" + fileName);
			FileReader in;
			in = new FileReader(f);
			char[] chars = new char[(int) f.length()];
			in.read(chars);
			String fileContent = new String(chars);
			fileContent = fileContent.replace("\n", "\\\n").replace("\r\n",
					"\\\r\n");
			return fileContent;
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return "";
	}

	public static String GetXSLFile(InputStream fileStream) throws IOException {
			String fileContent =IoUtil.readStream(fileStream);
			fileContent = fileContent.replace("\n", " ").replace("\r\n",
					" ");
		return fileContent;
	}
	
	public static String LocalStoreXSL(String varianceName, String fileName) throws IOException{
//		String content = GetXSLFile(fileName+".xsl");
//		String localStorage = "localStorage.setItem('"+varianceName+"','"+content+"');";
//		return localStorage;
		return "";
	}
	
	public static String LocalJSStorage(String name, String value){
		String localStorage = "localStorage.setItem('"+name+"','"+URLEncoder.encode(value)+"');";
		return localStorage;
	}
}
